import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/Toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});

  final Map<String, dynamic> userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  bool saving = false; // 是否正在保存
  String fileName = ""; // 记录图片名称
  bool isSelectPhoto = false;

  void _selectPhoto() async {
    ImagePicker picker = ImagePicker();
    XFile? file = await picker.pickImage(source: ImageSource.gallery); // 从相册选择
    if (file != null) {
      setState(() {
        widget.userInfo["avatar"] = file.path; // blob路径
      });
      isSelectPhoto = true;
      fileName = file.name;

      Navigator.pop(context);
    }
  }

  final TextEditingController _nickNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _nickNameController.text = widget.userInfo['nickName'];
  }

// 保存用户信息
  void _saveUserInfo() async {
    if (_nickNameController.text.isEmpty) {
      PromptAction.showFail("昵称不能为空");
      return;
    }
    RegExp reg = RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,18}$');
    if (!reg.hasMatch(_nickNameController.text)) {
      PromptAction.showFail("不符合允许中文、字母、数字和下划线，长度2-18字符");
      return;
    }
    if (!saving) {
      saving = true;
      if (isSelectPhoto) {
        // 说明需要上传
        // if (Platform.isAndroid) {
        //   PromptAction.showToast("Android上传头像");
        // }else if (Platform.isIOS) {
        //   PromptAction.showToast("IOS上传头像");
        // }else if (Platform.isOhos) {
        //   PromptAction.showToast("Ohos上传头像");
        // }
        FormData data = FormData.fromMap({
          "file": MultipartFile.fromBytes(
              await XFile(widget.userInfo["avatar"]).readAsBytes(), // 转二进制
              filename: fileName, // 文件名称
              contentType: DioMediaType("image", 'png')),
          "type": 'avatar'
        });
        // 将本地路径转化成二进制
        var res = await uploadPhotoAPI(data);
        print(res);
        PromptAction.showToast(res["url"]);

        setState(() {
          widget.userInfo["avatar"] = res["url"];
        });
        // return;
        isSelectPhoto = false;
        fileName = "";
      }

      // 保存昵称
      await updateUserInfoAPI({
        "nickName": _nickNameController.text,
        "avatar": widget.userInfo["avatar"] // 头像地址没有变化
      });
      PromptAction.showSuccess("修改昵称成功");
      eventBus.fire(LoginEventBus()); // 不用返回 因为可能只是改了头像
      saving = false;
    } else {
      PromptAction.showToast("正在保存中，请稍后再试");
    }
  }

  // 显示选择头像弹层
  void _showAvatarDialog() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            width: double.infinity,
            height: 180,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "拍照",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      _selectPhoto();
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.photo_album),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "相册",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.cancel_outlined),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "取消",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        });
  }


    getAvatarImage() {
    if (widget.userInfo['avatar'] != null && widget.userInfo['avatar'].isNotEmpty) {
      if (widget.userInfo['avatar'].startsWith('/data')) {
        return Image.file(
          File(widget.userInfo['avatar']),
          width: 30,
          height: 30,
        );
      } else {
        return Image.network(
          widget.userInfo['avatar'],
          width: 30,
          height: 30,
        );
      }
    } else {
      return Image.asset(
        'assets/images/avatar_1.jpg',
        width: 30,
        height: 30,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: _showAvatarDialog,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: getAvatarImage(),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                    // 默认值
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: _saveUserInfo,
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
